//
//  ReadingViewController.m
//  HappyBug
//
//  Created by liulei on 2018/10/16.
//  Copyright © 2018年 www.hc.com.cn. All rights reserved.
//
//https://www.jianshu.com/p/c59a5c92f859
#import "ReadingViewController.h"
#import "CustomCollectionViewCell.h"
#import "CollectionItem.h"
#define kScreenW  [UIScreen mainScreen].bounds.size.width
#define kScreenH  [UIScreen mainScreen].bounds.size.height
@interface ReadingViewController (){
    
    UICollectionView *mainConllectionView;
    
    UICollectionView *collection ;
    
    NSArray *topTitle;
    
    NSMutableArray *btoomTitle;
    
    NSArray *buttomImg;
    
    CollectionItem *items;
    
    NSMutableArray *data;
}



@end

@implementation ReadingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.barTintColor=[UIColor greenColor];
    
    [self initData];
    [self LoadUICollectionView];
    
}
-(void)initData{
    topTitle =@[@"为你推荐",@"查询",@"理财",@"为你推荐",@"查5询"];
    
    
    
    data =[[NSMutableArray alloc]init];
    
    for(int i=0;i<[topTitle count];i++){
        items =[[CollectionItem alloc]initWithName:@"京东" ImageName:[NSString stringWithFormat:@"img%d",i]];
        [data addObject:items];
    }
    
}

-(void)LoadUICollectionView{
    //1 UICollectionViewFlowLayout
    UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc]init];
    
    // 设置collectionView滚动方向--默认竖着的
    //[layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    
    //设置headerView的尺寸大小
    layout.headerReferenceSize = CGSizeMake(self.view.frame.size.width,30);
    //该方法也可以设置itemSize
    // layout.itemSize =CGSizeMake(30,50);
    
    
    // 2  UICollectionView
    collection =[[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
    
    //拉伸以后背景颜色-clearColor -window的黑颜色
    collection.backgroundColor=[UIColor whiteColor];
    collection.dataSource = self;
    collection.delegate = self;
    
    //列距
    layout.minimumInteritemSpacing = 30;
    //行距
    layout.minimumLineSpacing = 40;
    //item大大小
    //  layout.itemSize = CGSizeMake(([UIScreen mainScreen].bounds.size.width -60)/3, 200);
    
    [self.view addSubview:collection];
    
    //3.注册collectionViewCell
    [collection registerClass:[CustomCollectionViewCell class] forCellWithReuseIdentifier:@"cellID"];
    
    //4 注册headerView
    [collection registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableView"];
    
    //5 代理
    collection.delegate = self;
    collection.dataSource = self;
}


#pragma mark collectionView代理方法
//返回section个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return [data count];
}

//每个section的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [data count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CustomCollectionViewCell  *cell = (CustomCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"cellID" forIndexPath:indexPath];
    
    CollectionItem *item =data[indexPath.item];
    cell.btmlabel.text=item.titleNames;
    UIImage *image =[UIImage imageNamed:item.imageNames];
    cell.topImage.image=image;
    //条目cell 背景颜色
    cell.backgroundColor = [UIColor whiteColor];
    //点击手势。事件
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
    
    [cell addGestureRecognizer:longPress];
    
    return cell;
}

-(CGRect )getSizeWithStr:(NSString *)str
{
    UIFont *font = [UIFont boldSystemFontOfSize:15.0];
    return [str boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil] context:nil];
}
//设置每个item的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    CollectionItem *item =data[indexPath.item];
    return CGSizeMake(40.0f, 40.0f);
}

//footer的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    return CGSizeMake(30, 30);
}

//header的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(30, 30);
}

//设置每个item的UIEdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}


//设置每个item垂直间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}

//通过设置SupplementaryViewOfKind 来设置头部或者底部的view，其中 ReuseIdentifier 的值必须和 注册是填写的一致，本例都为 “reusableView”/ 头部view
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableView" forIndexPath:indexPath];
    headerView.backgroundColor =[UIColor whiteColor];
    UILabel *label = [[UILabel alloc] initWithFrame:headerView.bounds];
    
    //组名称
    NSString *topTxt= topTitle[indexPath.item];
    label.text = topTxt;
    label.font = [UIFont systemFontOfSize:18];
    [headerView addSubview:label];
    return headerView;
}

//点击item方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *clickTitle= data[indexPath.item];
    
    NSString *msg =[NSString stringWithFormat:@"点击的是%ld",clickTitle];
    NSLog(@"%@",msg);
}

- (void)longPressAction:(UILongPressGestureRecognizer *)longPress {
    
    NSLog(@"我被按了。。");\
    
    CustomCollectionViewCell *cell = (CustomCollectionViewCell *)longPress.view;
    NSIndexPath *cellIndexpath = [collection indexPathForCell:cell];
    
    [collection bringSubviewToFront:cell];
    
    self.isChange = NO;
    
    switch (longPress.state) {
        case UIGestureRecognizerStateBegan: {
            [self.cellAttributesArray removeAllObjects];
            for (int i = 0; i <data.count; i++) {
                [self.cellAttributesArray addObject:[collection  layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]]];
            }
            
        }
            break;
            
        case UIGestureRecognizerStateChanged: {
            
            cell.center = [longPress locationInView:collection];
            
            for (UICollectionViewLayoutAttributes *attributes in self.cellAttributesArray) {
                if (CGRectContainsPoint(attributes.frame, cell.center) && cellIndexpath != attributes.indexPath) {
                    self.isChange = YES;
                    NSString *imgStr = btoomTitle[cellIndexpath.row];
                    [data removeObjectAtIndex:cellIndexpath.row];
                    [data insertObject:imgStr atIndex:attributes.indexPath.row];
                    [collection moveItemAtIndexPath:cellIndexpath toIndexPath:attributes.indexPath];
                }
            }
        }
            break;
            
        case UIGestureRecognizerStateEnded: {
            
            if (!self.isChange) {
                cell.center = [collection layoutAttributesForItemAtIndexPath:cellIndexpath].center;
            }
        }
            break;
            
        default:
            break;
    }
    
    
    
    
}
- (NSMutableArray *)cellAttributesArray {
    if(_cellAttributesArray == nil) {
        _cellAttributesArray = [[NSMutableArray alloc] init];
    }
    return _cellAttributesArray;
}




@end
